#include "common/pch.h"

#include "auth/sha1.h"

#include <openssl/bn.h>
#include <stdarg.h>

#include <algorithm>

#include "auth/bignumber.h"

namespace auth
{

    Sha1Hash::Sha1Hash()
    {
        ctx_ = EVP_MD_CTX_new();
        md_ = EVP_sha1();
        EVP_DigestInit_ex(ctx_, md_, nullptr);
    }

    Sha1Hash::~Sha1Hash()
    {
        EVP_MD_CTX_free(ctx_);
    }

    void Sha1Hash::UpdateData(const unsigned char* dta, int len)
    {
        EVP_DigestUpdate(ctx_, dta, len);
    }

    void Sha1Hash::UpdateData(const std::string& str)
    {
        UpdateData((unsigned char const*)str.c_str(), (int)str.length());
    }

    void Sha1Hash::UpdateBigNumbers(BigNumber* bn0, ...)
    {
        va_list v;
        BigNumber* bn;

        va_start(v, bn0);
        bn = bn0;
        while (bn)
        {
            UpdateData(bn->AsByteArray(), bn->GetNumBytes());
            bn = va_arg(v, BigNumber*);
        }
        va_end(v);
    }

    void Sha1Hash::Initialize()
    {
        ctx_ = EVP_MD_CTX_new();
        md_ = EVP_sha1();
        EVP_DigestInit_ex(ctx_, md_, nullptr);
    }

    void Sha1Hash::Finalize(void)
    {
        unsigned int digest_len = 0;
        EVP_DigestFinal_ex(ctx_, mDigest, &digest_len);

        EVP_MD_CTX_free(ctx_);
        ctx_ = nullptr;
        md_ = nullptr;
    }

}